package cn.superchart.module.dev.api.utils;

import cn.hutool.core.util.ObjectUtil;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

@Slf4j
@Component
public class FreemarkerHelper {

    @Autowired
    private Configuration configuration;

    public StringTemplateLoader initTemplateLoader(Map<String,String> loaderMap){
        StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
        if(ObjectUtil.isNotEmpty(loaderMap)){
            for(String key:loaderMap.keySet()){
                stringTemplateLoader.putTemplate(key,loaderMap.get(key));
            }
        }
        configuration.setTemplateLoader(stringTemplateLoader);
        return stringTemplateLoader;
    }



    public String outString(String tempName,Map<String,Object> dataMap){
        StringWriter stringWriter = new StringWriter();
        try {
            Template template = configuration.getTemplate(tempName);
            template.process(dataMap,stringWriter);
        } catch (IOException | TemplateException e) {
            stringWriter.write("模板查询失败,请检查模板名称是否存在!");
        }
        return stringWriter.toString();
    }


}
